﻿using ProjBackEnd.Areas.BizProj.Models;
using ProjBackEnd.Areas.ExtPub.Models;
using ProjBackEnd.DBInstance;
using ProjBackEnd.Lib;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;

namespace ProjBackEnd.DAL
{
    /// <summary>
    /// 外部平台逻辑
    /// </summary>
    public class extPubWxLogic
    {
        /// <summary>
        /// 根据wx.login获取微信用户在系统中的身份
        /// </summary>
        /// <param name="_iPubid"></param>
        /// <param name="_strJsCode"></param>
        /// <param name="_strNickName"></param>
        /// <param name="_strAvatarUrl"></param>
        /// <returns></returns>
        internal static RespWxUserInfo GetWxUserInfo(int _iPubid, string _strJsCode, string _strNickName, string _strAvatarUrl)
        {
            RespWxUserInfo respReturn = new RespWxUserInfo();
            ExtPublicPlatformDataContext epctx = new ExtPublicPlatformDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                EXTPUB_PLATFORM entityPub = epctx.EXTPUB_PLATFORM.SingleOrDefault(n => n.pubid == _iPubid);
                if (entityPub == default(EXTPUB_PLATFORM)) throw new BizException(GlobalSettings.BIZMSG_NONEINFO + "@" + _iPubid.ToString());
                string strAppid = entityPub.appid;
                string strAppSecret = entityPub.appsecret;
                string strWxReq = "appid=" + strAppid + "&secret=" + strAppSecret + "&js_code=" + _strJsCode + "&grant_type=authorization_code";
                string strWxResp = WebUtil.GetMethod(GlobalSettings.URL_WX_CODE2SESSION, strWxReq);
                ExtWxRespCode2Session respWx = DataUtil.JsonDeserialize<ExtWxRespCode2Session>(strWxResp);
                //****TEST****
                //ExtRespCode2Session respWx = new ExtRespCode2Session
                //{
                //    openid = "o9Y3s4n8d_Mcp6wGHm2AM8x-isLQ",
                //    unionid = "o1xc5wOV8Bm29gjq0TlPWrNkoYyY"
                //};
                //*************
                DataUtil.WriteLog("WX_CODE2SESSION", strWxResp);
                if (respWx.errcode != 0) throw new BizException("微信用户认证失败");
                if (respWx == default(ExtWxRespCode2Session)) throw new BizException(GlobalSettings.BIZMSG_ANALYSISERR + "@" + strWxResp);
                int iPersonid = 0;
                EXTPUB_USER entityPubUser = epctx.EXTPUB_USER.SingleOrDefault(n => n.openid == respWx.openid && n.pubid == _iPubid);
                if (respWx.unionid == "") //用户未关注关联的公众号
                {
                    if (entityPubUser == default(EXTPUB_USER)) //新用户
                    {
                        if (entityPub.addpersonlb == 1) //当前平台用户允许在未加入开放平台时创建人员
                        {
                            iPersonid = epctx.SP_GETMASTERKEY("PERSONID");
                            if (iPersonid == 0) throw new BizException(GlobalSettings.BIZMSG_REFERROR + "@PERSONID");
                            epctx.SYS_PERSONTB.InsertOnSubmit(new SYS_PERSONTB
                            {
                                cellphone = "",
                                createdt = DateTime.Now,
                                creator = "AUTO",
                                personid = iPersonid,
                                personname = "USER" + new Random().Next(0, 10000000).ToString("00000000"),
                                wxunionid = respWx.unionid
                            });
                        }
                        epctx.EXTPUB_USER.InsertOnSubmit(new EXTPUB_USER
                        {
                            groupid = 0,
                            headimgurl = _strAvatarUrl ?? "",
                            nickname = _strNickName ?? "",
                            openid = respWx.openid,
                            personid = iPersonid,
                            pubid = _iPubid,
                            sessionkey = respWx.session_key,
                            subscribe = 1,
                            unionid = respWx.unionid
                        });
                    }
                    else iPersonid = entityPubUser.personid;
                }
                else //有unionid
                {
                    SYS_PERSONTB entityPerson = epctx.SYS_PERSONTB.SingleOrDefault(n => n.wxunionid == respWx.unionid);
                    if (entityPubUser == default(EXTPUB_USER)) //新用户
                    {
                        if (entityPerson == default(SYS_PERSONTB)) //没有为人员建过档
                        {
                            iPersonid = epctx.SP_GETMASTERKEY("PERSONID");
                            if (iPersonid == 0) throw new BizException(GlobalSettings.BIZMSG_REFERROR + "@PERSONID");
                            epctx.SYS_PERSONTB.InsertOnSubmit(new SYS_PERSONTB
                            {
                                cellphone = "",
                                createdt = DateTime.Now,
                                creator = "AUTO",
                                personid = iPersonid,
                                personname = "USER" + new Random().Next(0, 10000000).ToString("00000000"),
                                wxunionid = respWx.unionid
                            });
                        }
                        else
                        {
                            iPersonid = entityPerson.personid;
                            if (entityPerson.wxunionid != respWx.unionid) entityPerson.wxunionid = respWx.unionid;
                        }
                        epctx.EXTPUB_USER.InsertOnSubmit(new EXTPUB_USER
                        {
                            groupid = 0,
                            headimgurl = _strAvatarUrl ?? "",
                            nickname = _strNickName ?? "",
                            openid = respWx.openid,
                            personid = iPersonid,
                            pubid = _iPubid,
                            sessionkey = respWx.session_key,
                            subscribe = 1,
                            unionid = respWx.unionid
                        });
                    }
                    else //以当前平台为入口登录过
                    {
                        if (entityPubUser.personid == 0) //没有关联过人员
                        {
                            entityPerson = epctx.SYS_PERSONTB.SingleOrDefault(n => n.wxunionid == respWx.unionid);
                            if (entityPerson == default(SYS_PERSONTB)) //没有为人员建过档
                            {
                                iPersonid = epctx.SP_GETMASTERKEY("PERSONID");
                                if (iPersonid == 0) throw new BizException(GlobalSettings.BIZMSG_REFERROR + "@PERSONID");
                                epctx.SYS_PERSONTB.InsertOnSubmit(new SYS_PERSONTB
                                {
                                    cellphone = "",
                                    createdt = DateTime.Now,
                                    creator = "AUTO",
                                    personid = iPersonid,
                                    personname = "USER" + new Random().Next(0, 10000000).ToString("00000000"),
                                    wxunionid = respWx.unionid
                                });
                                entityPubUser.personid = iPersonid;
                            }
                            else
                            {
                                iPersonid = entityPerson.personid;
                                if (entityPerson.wxunionid != respWx.unionid) entityPerson.wxunionid = respWx.unionid;
                            }
                            if (entityPubUser.unionid == "") entityPubUser.unionid = respWx.unionid;
                        }
                        else
                        {
                            iPersonid = entityPubUser.personid;
                            entityPerson = epctx.SYS_PERSONTB.SingleOrDefault(n => n.personid == iPersonid);
                            if (entityPerson != default(SYS_PERSONTB) && string.IsNullOrEmpty(entityPerson.wxunionid))
                                entityPerson.wxunionid = respWx.unionid;
                            if (string.IsNullOrEmpty(entityPubUser.unionid)) entityPubUser.unionid = respWx.unionid;
                        }
                    }
                    List<EXTPUB_USER> lstPubUser = epctx.EXTPUB_USER.Where(n => n.unionid == respWx.unionid && n.personid == 0).ToList();
                    foreach (EXTPUB_USER _entity in lstPubUser) { _entity.personid = iPersonid; }
                }
                epctx.SubmitChanges();
                List<SysUserInfo> lstMember = epctx.VIEW_SYS_COMUSERINFO.Where(n => n.personid == iPersonid).AsEnumerable()
                                                                        .Select(n => new SysUserInfo
                                                                        {
                                                                            comcd = n.comcd,
                                                                            memberid = n.memberid,
                                                                            userid = n.userid,
                                                                            username = n.username
                                                                        }).ToList();
                //token逻辑
                string strWxToken = Guid.NewGuid().ToString("N");
                var cache = HttpRuntime.Cache;
                cache.Remove(respWx.openid + "@" + iPersonid);
                cache.Insert(respWx.openid + "@" + iPersonid, strWxToken, null, DateTime.Now.AddHours(2), TimeSpan.Zero);
                respReturn.result = new ResultWxUserLogin { memberlist = lstMember, openid = respWx.openid, personid = iPersonid, unionid = respWx.unionid, wxtoken = strWxToken };

            }
            catch (BizException ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90021;
                respReturn.statusMsg = ex.Message;
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90005;
                respReturn.statusMsg = "数据访问异常。" + ex.Message;
            }
            finally { if (epctx.Connection.State != ConnectionState.Closed) epctx.Connection.Close(); }
            return respReturn;
        }

        /// <summary>
        /// 检查微信token
        /// </summary>
        /// <param name="_strWxToken"></param>
        /// <param name="_strWxid"></param>
        /// <returns></returns>
        internal static bool CheckWxToken(string _strWxid, string _strWxToken)
        {
            //前端适配完毕后放开此逻辑
            return true;

            //var cache = HttpRuntime.Cache;
            //object tokenValue = cache.Get(_strWxid);
            //if (tokenValue == null) return false;
            //else
            //    return true;
        }

        internal static bool CheckWxUser(string _strUnionid, int _iPersonid)
        {
            bool bReturn = false;
            ExtPublicPlatformDataContext epctx = new ExtPublicPlatformDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                if (epctx.SYS_PERSONTB.Count(n => n.wxunionid == _strUnionid && n.personid == _iPersonid) == 0)
                    throw new BizException(GlobalSettings.BIZMSG_NONEINFO + "@" + _strUnionid + "&" + _iPersonid.ToString());
                bReturn = true;
            }
            catch (BizException ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
            }
            finally { if (epctx.Connection.State != ConnectionState.Closed) epctx.Connection.Close(); }
            return bReturn;
        }

        internal static void PubPlatformUserOpt(int _iPubid, string _strOpenid, int _iSubscribe)
        {
            ExtPublicPlatformDataContext epctx = new ExtPublicPlatformDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                EXTPUB_USER entityPubUser = epctx.EXTPUB_USER.SingleOrDefault(n => n.openid == _strOpenid && n.pubid == _iPubid);
                if (_iSubscribe == 0) //取消订阅
                {
                    if (entityPubUser == default(EXTPUB_USER)) return;
                    entityPubUser.subscribe = _iSubscribe;
                }
                else //订阅
                {
                    EXTPUB_PLATFORM entityPub = epctx.EXTPUB_PLATFORM.SingleOrDefault(n => n.pubid == _iPubid);
                    if (entityPub == default(EXTPUB_PLATFORM)) return;
                    string strAccessToken = CheckWxAccessToken(entityPub.appid, entityPub.appsecret);
                    if (strAccessToken == "") return;
                    //url?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
                    string strRespWx = WebUtil.GetMethod(GlobalSettings.URL_WX_GETUSERINFO, "access_token=" + strAccessToken + "&openid=" + _strOpenid + "&lang=zh_CN");
                    ExtWxRespUserInfo respWx = DataUtil.JsonDeserialize<ExtWxRespUserInfo>(strRespWx);
                    if (respWx.errcode != 0) throw new Exception("Get UserInfo Error@" + respWx.errmsg);
                    if (entityPubUser == default(EXTPUB_USER)) //新订阅用户
                    {
                        //if (respWx.unionid == "") return; //所关注的公众号没有加入开放平台
                        epctx.EXTPUB_USER.InsertOnSubmit(new EXTPUB_USER
                        {
                            groupid = respWx.groupid,
                            headimgurl = respWx.headimgurl,
                            nickname = respWx.nickname,
                            openid = respWx.openid,
                            personid = 0,
                            pubid = _iPubid,
                            subscribe = 1,
                            unionid = respWx.unionid,
                            sessionkey = ""
                        });
                    }
                    else
                    {
                        entityPubUser.unionid = string.IsNullOrEmpty(entityPubUser.unionid) ? respWx.unionid : entityPubUser.unionid;
                        entityPubUser.subscribe = _iSubscribe;
                    }
                }
                epctx.SubmitChanges();
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
            }
            finally { if (epctx.Connection.State != ConnectionState.Closed) epctx.Connection.Close(); }
        }


        /// <summary>
        /// 获取我的审批列表
        /// </summary>
        /// <param name="_iPersonid">人员id</param>
        /// <param name="_strComcd">公司代码</param>
        /// <param name="_strApplytp">审批类别</param>
        /// <param name="_strRevlb">审批标志</param>
        /// <param name="_iPageSize">每页记录数</param>
        /// <param name="_iCurrPage">当前页码</param>
        /// <returns></returns>
        internal static RespWxMyApprovalList GetWxMyApprovalList(int _iPersonid, string _strComcd, string _strApplytp, string _strRevlb, int _iPageSize = 10, int _iCurrPage = 1)
        {
            RespWxMyApprovalList respReturn = new RespWxMyApprovalList();
            bool hasNextPage = false;
            FinancialDataContext fcctx = new FinancialDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                if (_iPageSize == 0 || _iPageSize > GlobalSettings.MAXPAGESIZE) throw new BizException("单页数据量值有误");
                int iRecTotal = fcctx.VIEW_FIN_APPROVAL_ALL.Count(n => (_iPersonid == 0 ? false
                                                                                                                : ((n.revperson1 == _iPersonid && n.revlb1 == _strRevlb) || (n.revperson2 == _iPersonid && n.revlb2 == _strRevlb)))
                                                                                        && (string.IsNullOrEmpty(_strComcd) ? true : n.comcd == _strComcd)
                                                                                        && (string.IsNullOrEmpty(_strApplytp) ? true : n.applytp == _strApplytp));
                if ((iRecTotal / _iPageSize - _iCurrPage) > 0) hasNextPage = true;
                else if ((iRecTotal / _iPageSize - _iCurrPage) == 0)
                {
                    if ((iRecTotal % _iPageSize) > 0) hasNextPage = true;
                }
                respReturn.result = new ResultMyApprovalList
                {
                    hasnextpage = hasNextPage,
                    pagecount = iRecTotal == 0 ? 0 : iRecTotal / _iPageSize + 1,
                    reccount = iRecTotal,
                    approvallist = fcctx.VIEW_FIN_APPROVAL_ALL.Where(n => (_iPersonid == 0 ? false
                                                                                                                : ((n.revperson1 == _iPersonid && n.revlb1 == _strRevlb) || (n.revperson2 == _iPersonid && n.revlb2 == _strRevlb)))
                                                                                            && (string.IsNullOrEmpty(_strComcd) ? true : n.comcd == _strComcd)
                                                                                            && (string.IsNullOrEmpty(_strApplytp) ? true : n.applytp == _strApplytp))
                                                                                            .OrderByDescending(n => n.applyid)
                                                                                            .Take(_iPageSize * _iCurrPage).Skip(_iPageSize * (_iCurrPage - 1)).AsEnumerable()
                                                                                            .Select(n => new MyApprovalSummary
                                                                                            {
                                                                                                amt_apply = n.amt_apply.ToString(),
                                                                                                applyid = n.applyid,
                                                                                                applytp = n.applytp,
                                                                                                applytpnm = n.applytpnm,
                                                                                                comcd = n.comcd,
                                                                                                creator = n.creator,
                                                                                                desc = n.billtpnm,
                                                                                                hdltp = n.rplb,
                                                                                                hdltpnm = n.rplbnm,
                                                                                                submitdt = n.submitdt == null ? "" : ((DateTime)n.submitdt).ToString("yyyy-MM-dd HH:mm")
                                                                                            }).ToList()
                };
            }
            catch (BizException ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90021;
                respReturn.statusMsg = ex.Message;
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90005;
                respReturn.statusMsg = "数据访问异常。" + ex.Message;
            }
            finally { if (fcctx.Connection.State != ConnectionState.Closed) fcctx.Connection.Close(); }
            return respReturn;
        }

        /// <summary>
        /// 获取审批明细
        /// </summary>
        /// <param name="_iPersonid"></param>
        /// <param name="_iApplyid"></param>
        /// <param name="_strApplytp"></param>
        /// <param name="_strRevlb"></param>
        /// <returns></returns>
        internal static RespWxApprovalDetail GetWxApprovalDetail(int _iPersonid, int _iApplyid, string _strApplytp, string _strRevlb)
        {
            RespWxApprovalDetail respReturn = new RespWxApprovalDetail();
            FinancialDataContext fcctx = new FinancialDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                ResultApprovalDetail res;
                switch (_strApplytp.ToUpper())
                {
                    #region BILL
                    case GlobalSettings.APPLYTP_BILL:
                        VIEW_FIN_APPROVAL_BILL entityBill = fcctx.VIEW_FIN_APPROVAL_BILL.SingleOrDefault(n => n.billid == _iApplyid
                                                                                                                                                               && n.applytp == _strApplytp
                                                                                                                                                               && (_iPersonid == 0 ? false :
                                                                                                                                                                                                 ((n.reviewer1 == _iPersonid.ToString() && n.revlb1 == _strRevlb)
                                                                                                                                                                                                 || (n.reviewer2 == _iPersonid.ToString() && n.revlb2 == _strRevlb))));
                        if (entityBill == default(VIEW_FIN_APPROVAL_BILL)) throw new BizException(GlobalSettings.BIZMSG_NONEINFO);
                        res = new ResultApprovalDetail
                        {
                            amt_apply = (entityBill.rplb == GlobalSettings.FEELB_PAY ? entityBill.amt_pay : entityBill.amt_rec).ToString(),
                            amt_pre = entityBill.amt_pre.ToString(),
                            amt_settled = (entityBill.rplb == GlobalSettings.FEELB_PAY ? entityBill.amt_pay_ed : entityBill.amt_rec_ed).ToString(),
                            amt_total = (entityBill.rplb == GlobalSettings.FEELB_PAY ? entityBill.amt_pay : entityBill.amt_rec).ToString(),
                            applydesc = entityBill.billtpnm,
                            applyid = entityBill.billid,
                            applytp = entityBill.applytp,
                            creator = entityBill.creator,
                            cusid = entityBill.cusid,
                            cusnm = entityBill.cusnm,
                            hdltp = entityBill.rplb,
                            hdltpnm = (entityBill.rplb == GlobalSettings.FEELB_PAY ? "付款" : "收款"),
                            remark = entityBill.remark,
                            sortval = entityBill.sortval,
                            billid = entityBill.billid,
                            submitdt = (entityBill.submitdt == null ? "" : ((DateTime)entityBill.submitdt).ToString("yyyy-MM-dd HH:mm"))
                        };
                        break;
                    #endregion
                    #region FN
                    case GlobalSettings.APPLYTP_FN:
                        VIEW_FIN_APPROVAL_FN entityFN = fcctx.VIEW_FIN_APPROVAL_FN.SingleOrDefault(n => n.fnid == _iApplyid
                                                                                                                                                               && n.applytp == _strApplytp
                                                                                                                                                               && (_iPersonid == 0 ? false :
                                                                                                                                                                                                 ((n.reviewer1  == _iPersonid.ToString() && n.revlb1 == _strRevlb)
                                                                                                                                                                                                 || (n.reviewer2 == _iPersonid.ToString() && n.revlb2 == _strRevlb))));
                        if (entityFN == default(VIEW_FIN_APPROVAL_FN)) throw new BizException(GlobalSettings.BIZMSG_NONEINFO);
                        res = new ResultApprovalDetail
                        {
                            amt_apply = entityFN.amt_settle.ToString(),
                            amt_pre = entityFN.amt_pre.ToString(),
                            amt_settled = (entityFN.rplb == GlobalSettings.FEELB_PAY ? entityFN.amt_pay_ed : entityFN.amt_rec_ed).ToString(),
                            amt_total = (entityFN.rplb == GlobalSettings.FEELB_PAY ? entityFN.amt_pay : entityFN.amt_rec).ToString(),
                            applydesc = entityFN.billtpnm,
                            applyid = entityFN.fnid,
                            applytp = entityFN.applytp,
                            creator = entityFN.creator,
                            cusid = entityFN.cusid,
                            cusnm = entityFN.cusnm,
                            hdltp = entityFN.rplb,
                            hdltpnm = (entityFN.rplb == GlobalSettings.FEELB_PAY ? "付款" : "收款"),
                            remark = entityFN.remark,
                            sortval = entityFN.sortval,
                            billid = entityFN.billid,
                            submitdt = (entityFN.submitdt == null ? "" : ((DateTime)entityFN.submitdt).ToString("yyyy-MM-dd HH:mm"))
                        };
                        break;
                    #endregion
                    default: throw new BizException("申请单类别异常。@" + _strApplytp);
                }
                respReturn.result = res;
            }
            catch (BizException ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90021;
                respReturn.statusMsg = ex.Message;
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90005;
                respReturn.statusMsg = "数据访问异常。" + ex.Message;
            }
            finally { if (fcctx.Connection.State != ConnectionState.Closed) fcctx.Connection.Close(); }
            return respReturn;
        }

        /// <summary>
        /// 获取审批单所属的账单明细
        /// </summary>
        /// <param name="_iBillid">账单id</param>
        /// <returns></returns>
        internal static RespBizFee GetBillDetail(int _iBillid)
        {
            RespBizFee respReturn = new RespBizFee();
            BizProjDataContext bpctx = new BizProjDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                List<BizFeeExtInfo> lst = bpctx.VIEW_BIZ_FEEDETAILINFO.Where(n => n.billid == _iBillid).AsEnumerable()
                                                                                                        .Select(n => new BizFeeExtInfo
                                                                                                        {
                                                                                                            amt_payprice = n.amt_payprice,
                                                                                                            amt_paytotal = n.amt_paytotal,
                                                                                                            amt_recprice = n.amt_recprice,
                                                                                                            amt_rectotal = n.amt_rectotal,
                                                                                                            billid = n.billid,
                                                                                                            brand = n.brand,
                                                                                                            brandnm = n.brandnm,
                                                                                                            billpid = n.billpid,
                                                                                                            billpidnm = n.billpidnm,
                                                                                                            comcd = n.comcd,
                                                                                                            createdt = n.createdt.ToString("yyyy-MM-dd"),
                                                                                                            creator = n.creator,
                                                                                                            ctid = n.ctid,
                                                                                                            ctsubid = n.ctsubid,
                                                                                                            cuscd = n.cuscd,
                                                                                                            cusid = n.cusid,
                                                                                                            cusnm = n.cusnm,
                                                                                                            feeid = n.feeid,
                                                                                                            invotp = n.invotp,
                                                                                                            invotpnm = n.invotpnm,
                                                                                                            model = n.model,
                                                                                                            num = n.num,
                                                                                                            objdesc = n.objdesc,
                                                                                                            objtp = n.objtp,
                                                                                                            objtpnm = n.objtpnm,
                                                                                                            optlb = GlobalSettings.ENTITYOPERATION_NONE,
                                                                                                            pid = n.pid,
                                                                                                            piddesc = n.piddesc,
                                                                                                            projdtlid = n.projdtlid,
                                                                                                            projid = n.projid,
                                                                                                            projdtlnm = n.dtlnm,
                                                                                                            projnm = n.projnm,
                                                                                                            purchasdt = n.purchasdt.ToString("yyyy-MM-dd HH:mm"),
                                                                                                            remark = n.remark,
                                                                                                            spec = n.spec,
                                                                                                            taxrate = n.taxrate,
                                                                                                            rplb = n.rplb,
                                                                                                            unit = n.unit
                                                                                                        }).ToList();
                respReturn.result = new ResultBizFee { bizfeelist = lst };
            }
            catch (BizException ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90021;
                respReturn.statusMsg = ex.Message;
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90005;
                respReturn.statusMsg = "数据访问异常。" + ex.Message;
            }
            finally { if (bpctx.Connection.State != ConnectionState.Closed) bpctx.Connection.Close(); }
            return respReturn;
        }

        /// <summary>
        /// 更新绑定用户信息
        /// </summary>
        /// <param name="_strUserid"></param>
        /// <param name="_strPassword"></param>
        /// <param name="_strMemberid"></param>
        /// <param name="_iPersonid"></param>
        /// <param name="_strOptlb"></param>
        /// <returns></returns>
        internal static RespWxNullResultInfo UpdateBindMember(string _strUserid, string _strPassword, string _strMemberid, int _iPersonid, string _strOptlb)
        {
            RespWxNullResultInfo respReturn = new RespWxNullResultInfo();
            ExtPublicPlatformDataContext epctx = new ExtPublicPlatformDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                if (_iPersonid < 1) throw new BizException("人员编号非法");
                SYS_PERSONTB entityPerson = epctx.SYS_PERSONTB.SingleOrDefault(n => n.personid == _iPersonid);
                if (entityPerson == default(SYS_PERSONTB)) throw new BizException(GlobalSettings.BIZMSG_NONEINFO);
                if (entityPerson.personid != _iPersonid) throw new BizException("未找到人员信息");
                SYS_USERTB_extpub entityUser;
                switch (_strOptlb.ToUpper())
                {
                    case GlobalSettings.ENTITYOPERATION_INSERT:
                        string strPassEncrypt = DataUtil.EncryptPassword(_strPassword);
                        entityUser = epctx.SYS_USERTB_extpub.SingleOrDefault(n => n.userid == _strUserid && n.password == strPassEncrypt);
                        if (entityUser == default(SYS_USERTB_extpub)) throw new BizException("用户名或密码错误@" + _strUserid);
                        if (entityUser.personid > 0 && entityUser.personid != _iPersonid) throw new BizException("该账号已被其他用户绑定@" + _strUserid);
                        VIEW_SYS_COMUSERINFO entityComUser = epctx.VIEW_SYS_COMUSERINFO.SingleOrDefault(n => n.memberid == entityUser.memberid);
                        if (entityComUser == default(VIEW_SYS_COMUSERINFO)) throw new BizException(GlobalSettings.BIZMSG_NONEINFO);
                        if (epctx.VIEW_SYS_COMUSERINFO.Count(n => n.comcd == entityComUser.comcd && n.personid == _iPersonid && n.memberid != entityUser.memberid) > 0)
                            throw new BizException("同公司下不能绑定多个账号");
                        entityUser.personid = _iPersonid;
                        break;
                    case GlobalSettings.ENTITYOPERATION_DELETE:
                        entityUser = epctx.SYS_USERTB_extpub.SingleOrDefault(n => n.memberid == _strMemberid && n.personid == _iPersonid);
                        if (entityUser == default(SYS_USERTB_extpub)) throw new BizException(GlobalSettings.BIZMSG_NONEINFO);
                        entityUser.personid = 0;
                        break;
                    default: throw new BizException(GlobalSettings.BIZMSG_OPTLBERR);
                }
                epctx.SubmitChanges();
                respReturn.statusMsg = GlobalSettings.BIZMSG_OPTSUCC;
            }
            catch (BizException ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90021;
                respReturn.statusMsg = ex.Message;
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90005;
                respReturn.statusMsg = "数据访问异常。" + ex.Message;
            }
            finally { if (epctx.Connection.State != ConnectionState.Closed) epctx.Connection.Close(); }
            return respReturn;
        }

        /// <summary>
        /// 获取绑定用户信息
        /// </summary>
        /// <param name="_iPersonid"></param>
        /// <returns></returns>
        internal static RespWxBindMember GetBindMemberInfo(int _iPersonid)
        {
            RespWxBindMember respReturn = new RespWxBindMember();
            ExtPublicPlatformDataContext epctx = new ExtPublicPlatformDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                List<SysUserInfo> lstMember = epctx.VIEW_SYS_COMUSERINFO.Where(n => n.personid == _iPersonid).AsEnumerable()
                                                                        .Select(n => new SysUserInfo
                                                                        {
                                                                            comcd = n.comcd,
                                                                            memberid = n.memberid,
                                                                            userid = n.userid,
                                                                            username = n.username
                                                                        }).ToList();
                respReturn.result = new ResultBindMember { memberlist = lstMember };
            }
            catch (BizException ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90021;
                respReturn.statusMsg = ex.Message;
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90005;
                respReturn.statusMsg = "数据访问异常。" + ex.Message;
            }
            finally { if (epctx.Connection.State != ConnectionState.Closed) epctx.Connection.Close(); }
            return respReturn;
        }

        internal static InnerResultWxPubConfig GetPubInfo(int _iPubid)
        {
            InnerResultWxPubConfig resReturn;
            ExtPublicPlatformDataContext epctx = new ExtPublicPlatformDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                EXTPUB_PLATFORM entityPub = epctx.EXTPUB_PLATFORM.SingleOrDefault(n => n.pubid == _iPubid && n.pubowner == GlobalSettings.EXTPUBOWNER_WX);
                if (entityPub == default(EXTPUB_PLATFORM)) throw new Exception("Pubid Error" + _iPubid);
                resReturn = new InnerResultWxPubConfig
                {
                    aeskey = entityPub.aeskey,
                    appid = entityPub.appid,
                    appsecret = entityPub.appsecret,
                    apptoken = entityPub.token
                };
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                resReturn = default(InnerResultWxPubConfig);
            }
            finally { if (epctx.Connection.State != ConnectionState.Closed) epctx.Connection.Close(); }
            return resReturn;
        }

        internal static ResultWxUserLogin GetExtUserInfo(int _iPubid, string _strMemberid)
        {
            ResultWxUserLogin resReturn = new ResultWxUserLogin();
            ExtPublicPlatformDataContext epctx = new ExtPublicPlatformDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                VIEW_EXTPUB_USERINFO entityPubUser = epctx.VIEW_EXTPUB_USERINFO.FirstOrDefault(n => n.memberid == _strMemberid && n.pubid == _iPubid);
                if (entityPubUser == default(VIEW_EXTPUB_USERINFO)) throw new Exception("Can't Find Ext User@" + _strMemberid + "@" + 1);
                resReturn = new ResultWxUserLogin
                {
                    openid = entityPubUser.openid,
                    personid = entityPubUser.personid,
                    unionid = entityPubUser.unionid
                };

            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                resReturn = default(ResultWxUserLogin);
            }
            finally { if (epctx.Connection.State != ConnectionState.Closed) epctx.Connection.Close(); }
            return resReturn;
        }

        internal static void WxSendTemplateMessage(string _strPubAppid, string _strPubAppSecret, string _strToUser, string _strTemplate_id, string _strUrl, ExtWxSendMsgMiniApp _collecMiniprogram, ExtWxSendMsgData _collecMsgContent)
        {
            ExtWxReqSendMessage reqWx = new ExtWxReqSendMessage
            {
                data = _collecMsgContent,
                miniprogram = _collecMiniprogram,
                template_id = _strTemplate_id,
                touser = _strToUser,
                url = _strUrl
            };
            string strAccessToken = CheckWxAccessToken(_strPubAppid, _strPubAppSecret);
            try
            {
                if (string.IsNullOrEmpty(strAccessToken)) throw new Exception("AccessToken is Invalid");
                string strRespWx = WebUtil.PostMethod(GlobalSettings.URL_WX_SENDTEMPLATEMSG + strAccessToken, DataUtil.JsonSerializer(reqWx));
                ExtWxRespSendMsg respWx = DataUtil.JsonDeserialize<ExtWxRespSendMsg>(strRespWx);
                if (respWx == default(ExtWxRespSendMsg)) throw new Exception("SendMsg Failed@" + strRespWx);
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, respWx.msgid.ToString());
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
            }
        }

        internal static string CheckWxAccessToken(string _strAppid, string _strAppSecret)
        {
            var cache = HttpRuntime.Cache;
            object tokenValue = cache.Get(_strAppid);
            string strToken = "";
            if (tokenValue == null)
            {
                strToken = GetWxAccessToken(_strAppid, _strAppSecret);
                if (strToken == "") return "";
                cache.Insert(_strAppid, strToken, null, DateTime.Now.AddHours(2), TimeSpan.Zero);
                return strToken;
            }
            else
                return tokenValue.ToString();
        }

        private static string GetWxAccessToken(string _strAppid, string _strAppSecret)
        {
            string strRespWx = "";
            try
            {
                strRespWx = WebUtil.GetMethod(GlobalSettings.URL_WX_ACCESSTOKEN, "grant_type=client_credential&appid=" + _strAppid + "&secret=" + _strAppSecret);
                ExtWxRespAccessToken respWx = DataUtil.JsonDeserialize<ExtWxRespAccessToken>(strRespWx);
                if (respWx.errcode != 0) throw new Exception(respWx.errcode.ToString() + ";" + respWx.errmsg);
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, _strAppid + "@" + respWx.access_token);
                return respWx.access_token;
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message + ";" + strRespWx);
                return "";
            }
        }


        internal static void SendWxMsgApplyReq(string _strApplytp, int _iApplyid, string _strComcd, string _strMemberid, int _iSendPubid, ExtWxSendMsgData _collecPushContent)
        {
            InnerResultWxPubConfig resCfg = GetPubInfo(_iSendPubid);
            if (resCfg == default(InnerResultWxPubConfig)) return;
            ResultWxUserLogin resUser = GetExtUserInfo(_iSendPubid, _strMemberid);
            if (resUser == default(ResultWxUserLogin)) return;
            WxSendTemplateMessage(resCfg.appid,
                                                    resCfg.appsecret,
                                                    resUser.openid,
                                                    GlobalSettings.WX_TEMPLATEID_APPLYREQ,
                                                    GlobalSettings.URL_WX_SENDTEMPLATEMSG,
                                                    new ExtWxSendMsgMiniApp
                                                    {
                                                        appid = GlobalSettings.WXMINIAPPID,
                                                        pagepath = "pages/approval/approvaldetail/approvaldetail?applyid=" + _iApplyid.ToString() + "&applytp=" + _strApplytp + "&revlb=N&comcd=" + _strComcd
                                                    },
                                                    _collecPushContent);
        }
        internal static void SendWxMsgApplyResult(string _strMemberid, int _iSendPubid, ExtWxSendMsgData _collecPushContent)
        {
            InnerResultWxPubConfig resCfg = GetPubInfo(_iSendPubid);
            if (resCfg == default(InnerResultWxPubConfig)) return;
            ResultWxUserLogin resUser = GetExtUserInfo(_iSendPubid, _strMemberid);
            if (resUser == default(ResultWxUserLogin)) return;
            WxSendTemplateMessage(resCfg.appid,
                                                    resCfg.appsecret,
                                                    resUser.openid,
                                                    GlobalSettings.WX_TEMPLATEID_APPLYRESULT,
                                                    GlobalSettings.URL_WX_SENDTEMPLATEMSG,
                                                    default(ExtWxSendMsgMiniApp),
                                                    _collecPushContent);
        }



    }
}